package com.boot.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author Chunsheng.Zhang
 * @date 2021/1/6 16:29
 * @description : TODO
 */
@ConfigurationProperties(prefix = "config.jwt")
@Component
@Data
public class JWTUtil {

    private String secret;
    private long expire;
    private String header;


    /**
     * @description: 生成token
     * @author: ChunSheng.Zhang
     * @date: 2021/1/6 16:48
     * @param identityId
     * @return java.lang.String
     **/
    public String getToken (String identityId){

        Date nowDate = new Date();
        //过期时间
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(identityId)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }



    /**
     * @description: 解析token
     * @author: ChunSheng.Zhang
     * @date: 2021/1/6 16:49
     * @param token
     * @return io.jsonwebtoken.Claims
     **/
    public Claims getTokenClaim (String token) {

        try {
            return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }



    /**
     * @description: 判断session是否过期
     * @author: ChunSheng.Zhang
     * @date: 2021/1/6 16:50
     * @param expirationTime
     * @return boolean
     **/
    public boolean isTokenExpired (Date expirationTime) {

        return expirationTime.before(new Date());
    }

    // 省略 GET 和 SET
}
